package airportCoordination;

import Config.ConfigReader;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Launcher {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int active_port = 0;
		int pasive_port = 0;
		int monitor_port = 0;
		String sql_connection=null;
		String sql_user=null;
		String sql_password=null;
		
		BlockingQueue<Cargo> mailbox = new LinkedBlockingQueue<Cargo>();
		List<PacketLog> logbox = new LinkedList<PacketLog>();
		Lock lock = new ReentrantLock();

		try{
			Class.forName("com.mysql.jdbc.Driver").newInstance();
		}catch(Exception e){ System.out.print("FATAL ERROR. Loading SQL driver: " + e.getMessage() + "\n"); System.exit(666); }
	
		try{
			active_port = ConfigReader.getInt("active_port");
			pasive_port = ConfigReader.getInt("pasive_port");
			monitor_port = ConfigReader.getInt("monitor_port");
			sql_connection = new String("jdbc:mysql://" + ConfigReader.getString("sql_server") + "/" + ConfigReader.getString("sql_db"));
			sql_user = ConfigReader.getString("sql_user");
			sql_password = ConfigReader.getString("sql_pass");
		}
		catch (Exception ex) {
            System.out.print("Error reading configuration: " + ex.getMessage() + "\n");
        }
		
		Thread ih;
		Thread ap;
		SharedBoolean active = new SharedBoolean();
		
		Arrays.sort(args);
		int arg = Arrays.binarySearch(args, "-a");
		if (arg >= 0)
		{
			System.out.print("Running with " + args[arg] + "\n");
			active.set(true);
			ih = new Thread(new IncomingHandler(active_port, pasive_port, monitor_port, mailbox, active));
			ap = new Thread(new AirportPing(sql_connection, sql_user, sql_password, active));
		}
		else
		{
			active.set(false);
			ih = new Thread(new IncomingHandler(active_port, pasive_port, monitor_port, mailbox, active));
			ap = new Thread(new AirportPing(sql_connection, sql_user, sql_password, active));
		}
		Thread ph = new Thread(new PackageHandler(monitor_port, mailbox, sql_connection, sql_user, sql_password, logbox, lock));
		Thread ec = new Thread(new ErrorControl(logbox, lock, mailbox));
		
		Sender.randomize();
		Sender.set_logbox(logbox, lock);
		Sender.set_sqlconfig(sql_connection, sql_user, sql_password);
		
		ih.start();
		ph.start();
		ap.start();
		ec.start();
	}

}
